package com.jinsilu.freight.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.hjq.base.BaseDialog;
import com.hjq.base.action.BundleAction;
import com.hjq.base.action.ClickAction;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.jinsilu.freight.R;
import com.jinsilu.freight.action.ToastAction;
import com.jinsilu.freight.databinding.FinishedWaybillFragmentBinding;
import com.jinsilu.freight.helper.CommonHelper;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.model.HttpListData;
import com.jinsilu.freight.http.request.GetWaybillListApi;
import com.jinsilu.freight.http.response.DataBean;
import com.jinsilu.freight.http.response.WaybillBean;
import com.jinsilu.freight.other.MTLConstants;
import com.jinsilu.freight.ui.activity.WaybillDetailsActivity;
import com.jinsilu.freight.ui.adapter.FinishedWaybillAdapter;
import com.jinsilu.freight.ui.dialog.WaitDialog;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

import static com.hjq.http.EasyUtils.postDelayed;

public class FinishedWaybillFragment extends Fragment
        implements ClickAction, BundleAction, ToastAction, OnHttpListener {

    /**
     * 加载对话框
     */
    private BaseDialog mDialog;
    /**
     * 对话框数量
     */
    private int mDialogTotal;

    /**
     * 当前加载对话框是否在显示中
     */
    public boolean isShowDialog() {
        return mDialog != null && mDialog.isShowing();
    }

    /**
     * 显示加载对话框
     */
    public void showDialog() {
        mDialogTotal++;
        postDelayed(() -> {
            if (mDialogTotal > 0 && !isHidden()) {
                if (mDialog == null) {
                    mDialog = new WaitDialog.Builder(getContext())
                            .setCancelable(false)
                            .create();
                }
                if (!mDialog.isShowing()) {
                    mDialog.show();
                }
            }
        }, 300);
    }

    /**
     * 隐藏加载对话框
     */
    public void hideDialog() {
        if (mDialogTotal > 0) {
            mDialogTotal--;
        }

        if (mDialogTotal == 0 && mDialog != null && mDialog.isShowing() && !isHidden()) {
            mDialog.dismiss();
        }
    }

    /**
     * 根布局
     */
    private View mRootView;

    private FinishedWaybillFragmentBinding mBinding;

    private FinishedWaybillAdapter mAdapter;

    public static FinishedWaybillFragment newInstance() {
        return new FinishedWaybillFragment();
    }

    private Integer mCurrentPage = 1;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = FinishedWaybillFragmentBinding.inflate(inflater, container, false);
        mRootView = mBinding.getRoot();

        // 先屏蔽加载，有数据再放开
        mBinding.refresh.setEnableLoadMore(false);

        mBinding.recycler.setLayoutManager(new LinearLayoutManager(getContext()));
        DividerDecoration.builder(requireContext())
                .asSpace().size(10, TypedValue.COMPLEX_UNIT_DIP)
                .showSideDividers()
                .showFirstDivider()
                .showLastDivider()
                .build()
                .addTo(mBinding.recycler);
        mAdapter = new FinishedWaybillAdapter(new ArrayList<>());
        mAdapter.setEmptyView(R.layout.layout_empty_order_view);
        mBinding.recycler.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                WaybillBean bean = (WaybillBean) adapter.getData().get(position);
                Intent intent = new Intent(requireActivity(), WaybillDetailsActivity.class);
                intent.putExtra("waybill", bean);
                startActivity(intent);
            }
        });

        mAdapter.addChildClickViewIds(R.id.item_waybill_navigation, R.id.item_waybill_upload_unloading, R.id.item_waybill_more);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            int id = view.getId();
            if (id == R.id.item_waybill_navigation) {
                Intent intent = new Intent(getContext(), WaybillDetailsActivity.class);
                startActivity(intent);
            } else if (id == R.id.item_waybill_upload_unloading) {
                PhoneUtils.dial(MTLConstants.CUSTOMER_PHONE_NUMBER);
            } else if (id == R.id.item_waybill_more) {
//                toast("更多");
            } else {
                toast("Oh no, something wrong!!!");
            }
        });

        mBinding.refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mCurrentPage += 1;
                getWaybillData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mCurrentPage = 1;
                getWaybillData();
            }
        });

        return mRootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 未登录、未认证
        if (!CommonHelper.isLogin() || 1 != CommonHelper.getCertificationStatus()) {
            mBinding.refresh.setEnableRefresh(false);
            mAdapter.setEmptyView(R.layout.layout_empty_order_view);
        } else {
            mBinding.refresh.setEnableRefresh(true);
            mCurrentPage = 1;
            getWaybillData();
        }
    }

    private void getWaybillData() {

        // 未完成运单列表
        EasyHttp.get(this)
                .api(new GetWaybillListApi().setPageNum(mCurrentPage).setPageSize(10).setType(MTLConstants.WAYBILL_FINISHED))
                .request(new HttpCallback<HttpListData<WaybillBean>>(this) {

                    @Override
                    public void onSucceed(HttpListData<WaybillBean> data) {
                        CommonHelper.finishedLoading(mBinding.refresh);
                        List<WaybillBean> waybillBeans = data.getData();
                        if (null == waybillBeans || waybillBeans.isEmpty()) {
                            mAdapter.setEmptyView(R.layout.layout_empty_order_view);
                            mBinding.refresh.setEnableLoadMore(false);
                        } else {
                            mBinding.refresh.setEnableLoadMore(Integer.parseInt(data.getMessage()) / 10f > mCurrentPage);
                        }

                        if (mCurrentPage == 1)
                            mAdapter.setList(waybillBeans);
                        else
                            mAdapter.addData(waybillBeans);
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mBinding = null;
        if (isShowDialog()) {
            hideDialog();
        }
        mDialog = null;
    }

    @Nullable
    @Override
    public View getView() {
        return mRootView;
    }

    @Nullable
    @Override
    public Bundle getBundle() {
        return getArguments();
    }

    @Override
    public <V extends View> V findViewById(int id) {
        return null;
    }

    /**
     * {@link OnHttpListener}
     */

    @Override
    public void onStart(Call call) {
        showDialog();
    }

    @Override
    public void onSucceed(Object result) {
//        if (result instanceof HttpData) {
//            toast(((HttpData) result).getMessage());
//        }
    }

    @Override
    public void onFail(Exception e) {
        toast(e.getMessage());
        if (mAdapter.getData().isEmpty())
            mAdapter.setEmptyView(R.layout.layout_empty_order_view);
        CommonHelper.finishedLoading(mBinding.refresh);
    }

    @Override
    public void onEnd(Call call) {
        hideDialog();
    }
}
